package com.smzd.framework.system.actions;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.smzd.framework.annotation.Access;
import com.smzd.framework.core.actions.AbstractController;
import com.smzd.framework.core.business.IFGService;
import com.smzd.framework.system.business.GroupService;
import com.smzd.framework.system.business.RoleService;
import com.smzd.framework.system.domain.Group;
import com.smzd.framework.system.domain.Meeting;
import com.smzd.framework.system.domain.Role;
import com.smzd.framework.system.domain.User;
import com.smzd.framework.utils.JsonHelper;
import com.smzd.framework.utils.MeetingSessionHolder;
import com.smzd.framework.utils.db.RPage;

@Controller
@RequestMapping("/system/roles")
@Access(Role.TAG_ROLE_ROLES)
public class RoleController extends AbstractController<Role> {
	@Autowired
	private RoleService service;
	@Autowired
	private GroupService groupService;

	@Override
	protected IFGService<Role> getService() {
		return service;
	}

	@RequestMapping(value = "/add", method = RequestMethod.GET)
	@Override
	public String toAddPage(Map<String, Object> model, Role elem, BindingResult result) throws Exception {
		return super.toAddPage(model, elem, result);
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	@Override
	public String postAddData(Map<String, Object> model, Role elem, BindingResult result) throws Exception {
		return super.postAddData(model, elem, result);
	}

	@RequestMapping(method = RequestMethod.GET)
	@Override
	public String toListPage(Map<String, Object> model, Role elem, BindingResult result) throws Exception {
		return super.toListPage(model, elem, result);
	}

	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	@Override
	public String getListData(Map<String, Object> model, RPage<Role> page, BindingResult result) throws Exception {
		return super.getListData(model, page, result);
	}

	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	@Override
	public String toEditPage(Map<String, Object> model, Role elem, BindingResult result) throws Exception {
		elem = service.getItemById(elem.getId());
		return super.toEditPage(model, elem, result);
	}

	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	@ResponseBody
	@Override
	public String postEditData(Map<String, Object> model, Role elem, BindingResult result) throws Exception {
		return super.postEditData(model, elem, result);
	}

	@RequestMapping(value = "/remove", method = RequestMethod.POST)
	@ResponseBody
	@Override
	public String postRemoveData(Map<String, Object> model, Role elem, BindingResult result) throws Exception {
		return super.postRemoveData(model, elem, result);
	}

	// /////////////扩展功能--目标用户组获得角色的多对多编辑////////////////////
	/**
	 * toUserGroupsPage：导航到目标用户组所获得角色的编辑页面。<br>
	 * 注意：应当限制只有管理员用户可以进行此项操作！
	 * 
	 * @param model
	 * @param groupId
	 * @return
	 */
	@RequestMapping(value = "/group-{groupId}", method = RequestMethod.GET)
	@Access(Role.TAG_ROLE_GROUPS)
	public String toGroupRolesPage(Map<String, Object> model, @PathVariable("groupId") int groupId) throws Exception {
		Group group = groupService.getItemById(groupId);
		model.put("item", group);
		return getMyView("grouproles.ftl");
	}

	/**
	 * getUserGroupsData：获取目标用户组所获得的角色配置列表。<br>
	 * 目标用户组所获得的角色被排在前面，并且以复选框标志已经分配给当前用户组<br>
	 * 注意：应当限制只有管理员用户可以进行此项操作！
	 * 
	 * @param model
	 * @param groupId
	 * @param page
	 * @param result
	 * @return
	 */
	@RequestMapping(value = "/list/group-{groupId}", method = RequestMethod.POST)
	@ResponseBody
	@Access(Role.TAG_ROLE_GROUPS)
	public String getGroupRolesData(Map<String, Object> model, @PathVariable("groupId") int groupId, RPage<Role> page,
			BindingResult result) throws Exception {
		// page.setExt(String.valueOf(MeetingSessionHolder.getLoginUser().getId()));
		// page.setQuery(String.valueOf(groupId));
		User loginUser = MeetingSessionHolder.getLoginUser();
		Meeting meeting = MeetingSessionHolder.getMeeting();
		Map<String, Object> params = new HashMap<>();
		params.put("groupId", groupId);
		params.put("userId", loginUser.getId());
		params.put("meetingId", meeting.getId());
		page.setParams(params);
		int type = 0;
		if (loginUser.getOwner().getId().intValue() == meeting.getId().intValue()) {
			if (meeting.getOwner().getId().intValue() == loginUser.getId().intValue()) {
				// 这个时候不管loginUser到底是不是meeting0，应该应用meeting0规则
				type = 1;
			} else {
				// manager
				type = 3;
			}
		} else if (meeting.getOwner().getId().intValue() == loginUser.getId().intValue()) {
			// 这个地方要注意，虽然已经确定loginUser是meeting的owner，但是仍然不能确定loginUser是不是meeting0。
			// 如果loginUser不是meeting0，则当然是普通的owner了，也应该应用该规则；danger若loginUser是meeting0，仍然应该应用meeting0规则。
			// 此处的判断直接判断loginUser的id是不是1就行了。
			if (loginUser.getId().intValue() == 1) {
				type = 1;
			} else {
				// owner
				type = 2;
			}
		} else {
			// Not allowed
			throw new Exception("人员信息错误！");
		}

		return service.getGroupRoleListDataJson(page, type);
	}

	/**
	 * saveUserGroups：保存用户组所分配橘色的改变情况。<br>
	 * 只有新改变的部分数据需要提交服务器端进行处理。<br>
	 * 注意：应当限制只有管理员用户可以进行此项操作！
	 * 
	 * @param model
	 * @param groupId
	 * @param roleIds
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/edit/group-{groupId}", method = RequestMethod.POST)
	@ResponseBody
	@Access(Role.TAG_ROLE_GROUPS)
	public String saveGroupRoles(Map<String, Object> model, @PathVariable("groupId") int groupId,
			@RequestParam("roleIds") String roleIds) throws Exception {
		try {
			if (StringUtils.isEmpty(roleIds)) {
				return JsonHelper.getSuccessJsonString("没有任何变动提交！");
			}
			service.saveGroupRoles(groupId, roleIds);
			return JsonHelper.getSuccessJsonString("保存成功！");
		} catch (Exception e) {
			throw new Exception(e);
		}
	}

}
